package com.bluegalaxy.nhb.snservice.service.execute.impl;
import com.bluegalaxy.nhb.snservice.common.utils.StringUtil;
import com.bluegalaxy.nhb.snservice.domain.constant.CkConstant;
import com.bluegalaxy.nhb.snservice.domain.props.CkDbBaseProperties;
import com.bluegalaxy.nhb.snservice.service.execute.AddColumnService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


/**
 * @author:
 * @date: 2021/6/23 12:59
 * @description:
 */
@Service("AddColumnService")
public class AddColumnServiceImpl implements AddColumnService {

    private static Log log = LogFactory.getLog(AddColumnServiceImpl.class);
    @Autowired
    private CkDbBaseProperties dbBaseProperties;

    @Override
    public boolean addColumn(String columnName,String columnComment){
        Connection conn = null;
        Statement stat = null;

        String url = dbBaseProperties.getUrl();
        String username = dbBaseProperties.getUsername();
        String password = dbBaseProperties.getPassword();

        try {
            //连接数据库
            Class.forName(dbBaseProperties.getDriver());
            conn = DriverManager.getConnection(url, username, password);
            stat = conn.createStatement();
            String qSql = CkConstant.SQL_ADD_COLUMN;
            ClassPathResource classPathResource = new ClassPathResource("sql/"+qSql);

            InputStream inputStream =classPathResource.getInputStream();
            byte[] bdata = FileCopyUtils.copyToByteArray(inputStream);
            qSql = new String(bdata, StandardCharsets.UTF_8);

            qSql = qSql.replaceAll("column_name",columnName).replaceAll("column_comment","'"+columnComment+"'");

            if (StringUtil.isEmpty(qSql)){
                log.info("增加CK字段语句为空。。。。。。。。。。");
                return false;
            }
            stat.executeUpdate(qSql);

        } catch (IOException | SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            try {
                if (stat != null){
                    stat.close();
                }
                if (conn != null){
                    conn.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

        return true;
    }
}
